package fr.adfm.utils;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;


public class Utils {

    private static Context initialContext;

    private static final String PKG_INTERFACES = "org.jboss.ejb.client.naming";

    public static Context getInitialContext() throws NamingException {
	if ( initialContext == null ) {
	    Properties properties = new Properties();
	    properties.put( Context.URL_PKG_PREFIXES, PKG_INTERFACES );
	    initialContext = new InitialContext( properties );
	}
	return initialContext;
    }

    /**
     * 
     * @param chemin
     * @return
     */
    public static String getStringContentByURL( String chemin ) {
	String str = null;
	String retour = "";
	URL url;
	HttpURLConnection conn;
	try {
	    url = new URL( chemin );
	    conn = ( HttpURLConnection ) url.openConnection();
	    conn.setRequestMethod( "GET" );
	    //	    conn.setRequestProperty( "accept", "application/json" );
	    conn.setRequestProperty( "accept", "text/html, text/*" );
	    if ( conn.getResponseCode() == 200 ) {
		BufferedReader reader = new BufferedReader( new InputStreamReader( ( conn.getInputStream() ) ) );
		while ( ( str = reader.readLine() ) != null ) {
		    retour += str;
		}
	    }
	    conn.disconnect();
	}
	catch ( MalformedURLException e ) {
	    e.printStackTrace();
	}
	catch ( ProtocolException e ) {
	    e.printStackTrace();
	}
	catch ( IOException e ) {
	    e.printStackTrace();
	}

	return retour;
    }

    /**
     * Lecture du fichier de properties resourceFileName et recuperation de la valeur de key
     * @param resourceFileName nom du fichier de properties sans le suffixe
     * @param key
     * @return valeur de key si elle existe
     */
    public static String getResourceByName( String resourceFileName, String key ) {
	ResourceBundle resources = ResourceBundle.getBundle( resourceFileName, Locale.FRENCH );
	return resources.getString( key );
    }


}
